<?php
namespace App\Controller\App;

use App\Query\ConfigQuery;
use App\Query\UserTransferQuery;
use App\Repository\UserRepository;
use App\Repository\UserTransferRepository;

use App\Service\Code\CodeService;

class UserTransferController extends Controller
{
    // 日志
    public function index()
    {
        $query = $this->request->input('type') ? UserTransferQuery::toUser($this->auth()) : UserTransferQuery::user($this->auth());
        
        return $query->paginate(15)->toArray();
    }
    
    // 转帐
    public function to($id)
    {
        $user = $this->auth();
        
        $config = ConfigQuery::get();
        
        // 取出用户
        if(!$toUser = UserRepository::find($id))
        {
            $this->error('user_empty');
        }
        
        // if(!(new CodeService($user->phone))->check($this->input('code')))
        // {
        //     $this->error('code');
        // }
        
        // 互转类型
        $type = $this->input('type');

        // 转帐金额
        $money = (int) $this->input('money');
        
        // 组合字段
        $name = 'transfer_' . $type;
        
        // 判断配置中是否存在
        if(! ($config[$name] ?? 0))
        {
            $this->error('transfer_type');
        }
        
        // 倍数
        if(!$money || $money % $config['transfer'])
        {
            $this->error('double');
        }
        
        // 减资产
        if($user->makeMoney($type, $money, '转帐给【' . $toUser->username . '】'))
        {
            // 加资产
            $toUser->addMoney($type, $money, '来自【' . $user->username . '】转帐');
            
            // 税
            $tax = ConfigQuery::bi($config, $name . '_tax', $money);
            
            // 扣税
            $toUser->makeMoney($type, $tax, '来自【' . $user->username . '】转帐扣税', 'tax');
            
            // 记录
            UserTransferRepository::make()->create($user, $toUser, [
                'money_type' => $type,
                'money'      => $money,
                'tax'        => $tax
            ]);
        
            $this->message('ok');
        }
        
        $this->error($type);
    }
}
